package com.qiandw.config

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity

@EnableWebSecurity
open class SecurityConfig: WebSecurityConfigurerAdapter() {

    override fun configure(auth: AuthenticationManagerBuilder?) {
        //inMemoryAuthentication 从内存中获取
        auth!!.inMemoryAuthentication()
                .withUser("user").password("123456").roles("USER", "ANY")
                .and()
                .withUser("admin").password("123456").roles("ADMIN", "USER", "ANY")
//                .withUser("user").password("96e79218965eb72c92a549dd5a330112").roles("USER", "ANY")
//                .and()
//                .withUser("admin").password("96e79218965eb72c92a549dd5a330112").roles("ADMIN", "USER", "ANY")
//                .and()
//                .passwordEncoder(Md5PasswordEncoder())

        //jdbcAuthentication从数据库中获取，但是默认是以security提供的表结构
        //usersByUsernameQuery 指定查询用户SQL
        //authoritiesByUsernameQuery 指定查询权限SQL
        //auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(query).authoritiesByUsernameQuery(query);

        //注入userDetailsService，需要实现userDetailsService接口
        //auth.userDetailsService(userDetailsService);
    }

    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()//配置安全策略
                .antMatchers("/", "/home").permitAll()//定义/请求不需要验证
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().hasRole("ANY")
                .and()
                .formLogin()//使用form表单登录
                .and()
                .sessionManagement()
                .maximumSessions(1)
                .maxSessionsPreventsLogin(true)
//                .expiredUrl("/")
                .and()
                .and()
                .logout()
                .logoutUrl("/logout")
                .and()
                .csrf().disable()

    }

}